//
//  LanguagePicker.m
//  SleepingElf
//
//  Created by karong on 2023/10/27.
//

#import "LanguagePicker.h"
#import "AppDelegate.h"

@interface LanguagePicker () <UIPickerViewDelegate, UIPickerViewDataSource>
@property (weak, nonatomic) IBOutlet UIPickerView *picker;
@property (weak, nonatomic) IBOutlet UIView *mainView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *mainViewBottom;
@property (nonatomic, assign) NSInteger selectIndex;
@end

@implementation LanguagePicker

- (void)viewDidLoad {
    [super viewDidLoad];
    self.enableDismissWhenTapBackgroundView = YES;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.picker.subviews[1].backgroundColor = UIColor.clearColor;
        [self.picker selectRow:MAX(0, appConfig.languageType) inComponent:0 animated:NO];
    });
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return 2;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    NSString * text = languageStrArray[row];
    UIColor *  color = [UIColor colorFromHexRGB:@"ffffff"];
    UILabel *label = [[UILabel alloc]init];
    label.textAlignment = 1;
    label.font = [UIFont systemFontOfSize:20 weight:(UIFontWeightMedium)];
    label.textColor = color;
    label.text = text;
    return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component API_UNAVAILABLE(tvos) {
    self.selectIndex = row;
}

- (IBAction)closeAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)saveAction:(id)sender {
    if (appConfig.languageType == self.selectIndex) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else {
        appConfig.languageType = self.selectIndex;
        [self dismissViewControllerAnimated:YES completion:^{
            [AppLanguage setUserLanguageType:appConfig.languageType];
        }];
    }
}

@end
